import Cookies from 'js-cookie'
import Vue from 'vue'
import { MessageBox, Message } from 'element-ui'
import command from '@/utils/command'
Vue.use(command)
const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  hideSidebar: false,
  systemTitle: '扁鹊中医后台管理',
  rela: 0
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  HIDE_SIDEBAR: (state, playlod) => {
    state.hideSidebar = playlod
  },
  SET_SYSTEM_TITLE: (state, playlod) => {
    state.systemTitle = playlod
  }
}

const actions = {
  toggleSideBar ({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar ({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice ({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  hideSidebar ({ commit }, playlod) {
    commit('HIDE_SIDEBAR', playlod)
  },
  async getSystemTitle ({ commit, state }, playlod) {
    if (state.systemTitle) {
      return state.systemTitle
    } else {
      const res = await command.executeCommand({
        api: '/api/SelectByRela/MetaApp',
        params: {
          index: 0,
          pageSize: 0,
          rela: 10
        },
        data: ["id", "应用名"]
      })
      if (res.flag) {
        let data = res.data.filter(e => e.id == state.rela)
        if (data && data.length) {
          commit('SET_SYSTEM_TITLE', data[0]['应用名'])
          return data[0]['应用名']
        }
      }

    }
  },
  async getPageTotal ({ commit, state }, { busiName, filterAnd = [], COLUMNS = [] }) {
    const res = await command.executeCommand({
      api: `/api/SelectByCondsCount/${busiName}`,
      params: {},
      data: {
        "CONDS": filterAnd,
        COLUMNS
      }
    })
    if (res.flag) {
      return res.data
    }
  },
  async canDeleteRow ({ commit, state }, { busiName, rowId = '' }) {
    const res = await command.executeCommand({
      api: `/api/SelectFun/IfCanDel`,
      data: {
        "optype": busiName,
        "rowid": rowId
      }
    })
    if (res.flag) {
      let val = false
      if (res.data.ifcan_del == "TRUE") {
        val = true
      }
      if (!val) {
        Message.error('不能删除该数据')
      }
      return val
    } else {
      return false
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
